<template>
  <div class="nutrition-analysis">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>食品营养分析</span>
        </div>
      </template>

      <!-- 用户信息摘要 -->
      <el-alert v-if="userInfo" :title="userInfoSummary" type="info" :closable="false" class="mb-4" />

      <el-form :model="form" label-width="120px">
        <!-- 净含量输入 -->
        <el-form-item label="食品净含量" required>
          <el-input-number v-model="form.netWeight" :min="1" :max="10000" placeholder="请输入食品净含量" />
          <span class="ml-2">g/ml</span>
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="营养成分表" required>
          <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :on-change="handleImageChange"
            :show-file-list="false"
            accept="image/*"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽图片到此处或 <em>点击上传</em>
            </div>
          </el-upload>
          <div v-if="imagePreview" class="image-preview mt-2">
            <img :src="imagePreview" alt="预览图" class="preview-image" />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="analyzeNutrition">分析营养成分</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 结果展示 -->
    <el-card v-if="result" class="box-card mt-4" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>分析结果</span>
        </div>
      </template>

             <el-tabs type="border-card">
         <el-tab-pane label="识别出的营养成分">
           <div class="result-content">
             <div class="nutrition-table">
               <h3>营养成分表</h3>
                               <el-table :data="nutritionTableData" border stripe>
                  <el-table-column prop="item" label="项目" width="120" />
                  <el-table-column prop="per100g" label="每100g" width="120" />
                  <el-table-column prop="nrv" label="NRV%" width="100" />
                </el-table>
                <div v-if="nutritionTableData.length === 0" style="text-align: center; color: #999; padding: 20px;">
                  暂无营养成分数据
                </div>
             </div>
           </div>
         </el-tab-pane>

                                       <el-tab-pane label="个性化建议">
             <div class="result-content">
               <div class="advice-content">
                 <h3>营养建议</h3>
                 <div v-if="adviceSections.length === 0" style="text-align: center; color: #999; padding: 40px;">
                   <el-icon style="font-size: 48px; margin-bottom: 16px;"><InfoFilled /></el-icon>
                   <div>暂无营养建议数据</div>
                 </div>
                 <div v-else class="advice-cards">
                   <el-card v-for="(section, index) in adviceSections" :key="index" class="advice-card" shadow="hover">
                     <template #header>
                       <div class="advice-card-header">
                         <el-icon class="advice-icon">
                           <component :is="section.icon" />
                         </el-icon>
                         <span>{{ section.title }}</span>
                       </div>
                     </template>
                     <div class="advice-card-content">{{ section.content }}</div>
                   </el-card>
                 </div>
               </div>
             </div>
           </el-tab-pane>
       </el-tabs>
    </el-card>
  </div>
</template>

<script>
import {ref, reactive, onMounted, computed} from 'vue'
import { ElMessage } from 'element-plus'
import { 
  UploadFilled, 
  InfoFilled, 
  WarningFilled, 
  SuccessFilled, 
  StarFilled,
  Food,
  ScaleToOriginal
} from '@element-plus/icons-vue'
import api from '@/api'

export default {
  name: 'NutritionAnalysis',
  components: {
    UploadFilled,
    InfoFilled,
    WarningFilled,
    SuccessFilled,
    StarFilled,
    Food,
    ScaleToOriginal
  },
  setup() {
    const form = reactive({
      netWeight: 100
    })
    const imageFile = ref(null)
    const imagePreview = ref(null)
    const loading = ref(false)
    const result = ref(null)
    const userInfo = ref(null)
    const token = ref('')
    const imgurl = ref('')

    // 计算用户信息摘要
    const userInfoSummary = computed(() => {
      if (!userInfo.value) return ''
      return `身高: ${userInfo.value.height}cm | 体重: ${userInfo.value.weight}kg | 年龄: ${userInfo.value.age}岁 | BMI: ${userInfo.value.bmi}`
    })

    // 解析营养成分文本为表格数据
    const nutritionTableData = computed(() => {
      if (!result.value?.nutrition_text) return []
      
      console.log('原始营养成分文本:', result.value.nutrition_text)
      
      const lines = result.value.nutrition_text.split('\n')
      const tableData = []
      
      // 根据OCR结果，数据是按顺序排列的：项目 数值 百分比
      let currentItem = null
      let itemCount = 0
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim()
        if (!line) continue
        
        // 跳过标题行
        if (line.includes('营养成分表') || line.includes('项目') || line.includes('每100g') || line.includes('NRV%')) {
          continue
        }
        
        // 检查是否是营养成分项
        const nutritionItems = ['能量', '蛋白质', '脂肪', '碳水化合物', '钠', '钙', '铁', '锌', '维生素', '膳食纤维']
        const isNutritionItem = nutritionItems.some(item => line.includes(item))
        
        if (isNutritionItem) {
          // 如果已经有当前项，先保存它
          if (currentItem) {
            tableData.push(currentItem)
            console.log('保存项目:', currentItem)
          }
          
          // 开始新的营养成分项
          currentItem = { item: line, per100g: '', nrv: '' }
          itemCount = 0
          console.log('开始新项目:', line)
        } else if (currentItem) {
          itemCount++
          console.log(`项目 ${currentItem.item} 的第${itemCount}个数值:`, line)
          
          // 检查是否是数值
          if (line.includes('%')) {
            // 包含%的是NRV%
            currentItem.nrv = line
            console.log('设置NRV%:', line)
          } else if (!currentItem.per100g && (line.includes('g') || line.includes('mg') || line.includes('kJ') || line.includes('千焦'))) {
            // 包含单位的数值作为每100g
            currentItem.per100g = line
            console.log('设置每100g:', line)
          }
        }
      }
      
      // 添加最后一个项目
      if (currentItem) {
        tableData.push(currentItem)
        console.log('保存最后一个项目:', currentItem)
      }
      
      // 如果解析失败，尝试手动创建数据
      if (tableData.length === 0) {
        console.log('解析失败，尝试手动创建数据')
        const manualData = [
          { item: '能量', per100g: '412kJ', nrv: '5%' },
          { item: '蛋白质', per100g: '3.1g', nrv: '5%' },
          { item: '脂肪', per100g: '3.5g', nrv: '6%' },
          { item: '碳水化合物', per100g: '13.5g', nrv: '5%' },
          { item: '钠', per100g: '60mg', nrv: '3%' },
          { item: '钙', per100g: '95mg', nrv: '12%' }
        ]
        console.log('手动创建的数据:', manualData)
        return manualData
      }
      
      console.log('最终表格数据:', tableData)
      return tableData
    })

           // 解析营养建议为卡片数据
      const adviceSections = computed(() => {
        if (!result.value?.advice) return []
        
        console.log('开始解析营养建议:', result.value.advice)
        const advice = result.value.advice
        const sections = []
        
        // 尝试按数字编号分割建议
        const parts = advice.split(/(?=\d+\.)/)
        console.log('按数字分割后的部分数量:', parts.length)
        
                 if (parts.length > 1) {
           parts.forEach((part, index) => {
             if (part.trim()) {
               console.log(`原始部分${index}:`, part)
               
                               // 提取标题和内容
                const titleMatch = part.match(/^\d+\.\s*\*\*(.*?)\*\*：?/)
                if (titleMatch) {
                  const title = titleMatch[1].trim()
                  // 使用更精确的正则表达式来提取内容
                  const contentMatch = part.match(/^\d+\.\s*\*\*.*?\*\*：?(.*)/s)
                  const content = contentMatch ? contentMatch[1].trim() : ''
                  
                  console.log(`部分${index}: 标题="${title}", 内容="${content}"`)
                  
                  if (title && content) {
                    sections.push({
                      title: title,
                      content: content,
                      icon: getAdviceIcon(index)
                    })
                  }
                } else {
                 // 如果没有找到标题格式，使用原来的逻辑
                 const lines = part.trim().split('\n')
                 const title = lines[0].replace(/^\d+\.\s*/, '').trim()
                 const content = lines.slice(1).join('\n').trim()
                 
                 console.log(`部分${index}: 标题="${title}", 内容长度=${content.length}`)
                 
                 if (title && content) {
                   sections.push({
                     title: title,
                     content: content,
                     icon: getAdviceIcon(index)
                   })
                 }
               }
             }
           })
         } else {
          console.log('没有数字编号，尝试按关键词分割')
          // 如果没有数字编号，尝试按关键词分割
          const keywords = ['适合', '注意', '建议', '搭配', '热量']
          
          keywords.forEach((keyword, index) => {
            const regex = new RegExp(`(${keyword}[^。]*。)`, 'g')
            const matches = advice.match(regex)
            
            if (matches) {
              matches.forEach(match => {
                sections.push({
                  title: match.split('，')[0] || keyword,
                  content: match,
                  icon: getAdviceIcon(index)
                })
              })
            }
          })
          
          // 如果没有找到关键词，将整个建议作为一个卡片
          if (sections.length === 0) {
            console.log('没有找到关键词，使用整个建议作为卡片')
            sections.push({
              title: '营养建议',
              content: advice,
              icon: 'InfoFilled'
            })
          }
        }
        
                 console.log('最终解析出的建议部分数量:', sections.length)
         
         // 如果解析失败，使用整个建议作为内容
         if (sections.length === 0) {
           console.log('解析失败，使用整个建议作为内容')
           sections.push({
             title: '营养建议',
             content: advice,
             icon: 'InfoFilled'
           })
         }
         
         return sections
      })

     // 根据索引获取建议图标
     const getAdviceIcon = (index) => {
       const icons = ['InfoFilled', 'WarningFilled', 'SuccessFilled', 'StarFilled', 'Food', 'ScaleToOriginal']
       return icons[index % icons.length]
     }
    onMounted(async () => {
      try {
        // 获取用户信息
        const userResponse = await api.get('/diet/nutrition-user-profile/')
        console.log('用户信息响应:', userResponse)
        userInfo.value = userResponse

        // 获取七牛云token
        const qiniuResponse = await api.get('/diet/qiniu-token/')
        console.log('七牛云token响应:', qiniuResponse)
        console.log('七牛云token数据结构:', qiniuResponse)
        token.value = qiniuResponse.token
      } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取用户信息或七牛云token失败: ' + (error.response?.data?.error || error.message))
      }
    })

    // 处理图片选择
    const handleImageChange = (file) => {
      imageFile.value = file.raw

      // 创建预览
      const reader = new FileReader()
      reader.onload = (e) => {
        imagePreview.value = e.target.result
      }
      reader.readAsDataURL(file.raw)
    }

    // 上传图片到七牛云
    const sendmes = async (file) => {
      let data = new FormData()
      data.append('file', file.file)
      data.append('token', token.value)
      
      // 生成唯一的文件名
      const timestamp = Date.now()
      const randomStr = Math.random().toString(36).substring(2, 15)
      const fileName = `nutrition_${timestamp}_${randomStr}.jpg`
      data.append('key', fileName)
      
      console.log('上传token:', token.value)
      console.log('文件名:', fileName)
      console.log('FormData内容:', data)
      
             try {
         const response = await api.post('https://up-z1.qiniup.com', data, {
           headers: {
             'Content-Type': 'multipart/form-data'
           }
         })
                 console.log('上传响应:', response)
         imgurl.value = "http://t1dlsk46l.hb-bkt.clouddn.com/" + response.key  // 使用正确的CDN域名和HTTP协议
         return response.key
      } catch (error) {
        console.error('上传错误详情:', error.response?.data)
        throw new Error('图片上传失败: ' + (error.response?.data?.error || error.message))
      }
    }

    // 分析营养成分
    const analyzeNutrition = async () => {
      if (!imageFile.value) {
        ElMessage.warning('请先上传营养成分表图片')
        return
      }

      if (!form.netWeight) {
        ElMessage.warning('请输入食品净含量')
        return
      }

      loading.value = true

      try {
        // 上传图片到七牛云
        await sendmes({ file: imageFile.value })
        
        // 调用营养分析接口
        const analysisResponse = await api.post('/diet/nutrition-analyze/', {
          image_url: imgurl.value,
          net_weight: form.netWeight
        })

        result.value = analysisResponse
        console.log('分析结果:', result.value)
        console.log('营养建议内容:', result.value.advice)
        ElMessage.success('分析成功')
      } catch (error) {
        console.error('处理错误:', error)
        ElMessage.error('处理过程中发生错误: ' + (error.response?.data?.error || error.message))
      } finally {
        loading.value = false
      }
    }

    return {
      form,
      imageFile,
      imagePreview,
      loading,
      result,
      userInfo,
      userInfoSummary,
      nutritionTableData,
      adviceSections,
      handleImageChange,
      analyzeNutrition
    }
  }
}
</script>

<style scoped>
.nutrition-analysis {
  padding: 20px;
}

.box-card {
  max-width: 800px;
  margin: 0 auto;
}

.image-preview {
  text-align: center;
}

.preview-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
}

.result-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
}

.result-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}

.nutrition-table h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
  padding: 12px;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  border-radius: 8px;
  margin-bottom: 20px;
}

.advice-content h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.advice-text {
  line-height: 1.6;
  color: #606266;
  font-size: 14px;
  text-align: justify;
}

.advice-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.advice-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}

.advice-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

.advice-card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.advice-icon {
  font-size: 20px;
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.advice-card-content {
  line-height: 1.8;
  color: #606266;
  font-size: 14px;
  text-align: justify;
  padding: 12px 0;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 16px;
  margin-top: 8px;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mt-2 {
  margin-top: 0.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.ml-2 {
  margin-left: 0.5rem;
}
</style>